package com.hdoit.ares.web.cust.apis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.hdoit.ares.logical.cust.model.CustPoster;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustPosterService;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.viewmodel.cust.CustPosterSearch;
import com.hdoit.ares.selfcommon.utils.QRCodeUtils;
import com.tennetcn.common.enums.pub.YesOrNo;
import com.tennetcn.common.logical.file.model.OssFileInfo;
import com.tennetcn.common.logical.file.service.IOssFileInfoService;
import com.tennetcn.common.logical.viewmodel.common.QRCodeIndex;
import com.tennetcn.common.selfcommon.enums.common.QRCodeLevel;
import com.tennetcn.component.webapi.BaseApi;
import com.tennetcn.component.webapi.ResponseModel;
import com.tennetcn.component.webapi.ResponseStatus;
import com.tennetcn.web.cbase.ApiAuthPassport;

@Controller
@RequestMapping(value = "/api/v1/custPosterAresApi/",method = {RequestMethod.GET,RequestMethod.POST},produces="application/json;charset=utf-8")
@Api(value = "/api/v1/custPosterAresApi/")
@CrossOrigin(origins = "*",maxAge = 3600)
public class CustPosterAresApi extends BaseApi{

	private ICustPosterService custPosterService;
	private IOssFileInfoService fileInfoService;
	private ICustomerService customerService;
	
	public ICustomerService getCustomerService() {
		return customerService;
	}

	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}

	public IOssFileInfoService getFileInfoService() {
		return fileInfoService;
	}

	@Resource
	public void setFileInfoService(IOssFileInfoService fileInfoService) {
		this.fileInfoService = fileInfoService;
	}

	public ICustPosterService getCustPosterService() {
		return custPosterService;
	}

	@Resource
	public void setCustPosterService(ICustPosterService custPosterService) {
		this.custPosterService = custPosterService;
	}



	private final String custPosterListApi = "custPosterList";
	private final String posterDetailApi = "posterDetail";
	

	
	@ResponseBody
	@ApiAuthPassport
	@RequestMapping(value = custPosterListApi)
	@ApiOperation(notes=custPosterListApi,httpMethod = "POST",value = "海报列表")
	public String custPosterList(Integer pageNum,String posterType){
		ResponseModel rm = new ResponseModel();
		String publicUrl = "http://test-1254043822.cosgz.myqcloud.com";
		CustPosterSearch custPosterSearch = new CustPosterSearch();
		
		custPosterSearch.setPageNum(pageNum);
		custPosterSearch.setPosterType(posterType);
		
		List<CustPoster>custPosters = custPosterService.queryListApi(custPosterSearch);
		
		for(CustPoster  custPoster:custPosters){
			OssFileInfo ossFileInfo = fileInfoService.queryModel(custPoster.getPosterImg());
			custPoster.setPosterUrl(publicUrl+ossFileInfo.getFilename());
		}
		
		List<String> optionParams = new ArrayList<String>();
		optionParams.add("id");
		optionParams.add("posterType");
		optionParams.add("posterUrl");
		optionParams.add("descript");
		optionParams.add("createDate");
	
		rm.setStatus(ResponseStatus.success);
		rm.setMessage("ok");
		rm.putList("posterList", custPosters, optionParams);
		
		return rm.toJson();
	}
	
	
	@ResponseBody
	@RequestMapping(value = posterDetailApi)
	@ApiOperation(notes = posterDetailApi,httpMethod = "POST",value = "海报详情")
	public void posterDetail(String posterId,String addCard,String name,String phone,HttpServletRequest request,HttpServletResponse response){
		CustPoster custPoster = custPosterService.queryModel(posterId);
		BufferedImage backgroundImage = fileInfoService.getOSSBufferedImage(custPoster.getPosterImg());
		Customer customer = customerService.queryModel(getLoginId());
		String qrUrl = "http://www.hdoit.com/ares/wechat/cust/appShareRegister/registered?shareCode="+customer.getUserIdentity();
		QRCodeIndex qrCodeIndex  = new QRCodeIndex();
		qrCodeIndex.setContent(qrUrl);
		qrCodeIndex.setLogo("0");
		//得到二维码
		Map<EncodeHintType, Object> hints =QRCodeUtils.getDecodeHintType();
		if(QRCodeLevel.H.equals(qrCodeIndex.getLevel())){
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		}else if(QRCodeLevel.Q.equals(qrCodeIndex.getLevel())){
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);
		}else if(QRCodeLevel.M.equals(qrCodeIndex.getLevel())){
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		}else if(QRCodeLevel.L.equals(qrCodeIndex.getLevel())){
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
		}
		
		BufferedImage qrcodeImg=QRCodeUtils.getQR_CODEBufferedImage(qrCodeIndex.getContent(),hints);
		if(YesOrNo.yes.equals(qrCodeIndex.getLogo())){
			String logoPath = request.getServletContext().getRealPath("/WEB-INF/content/images/logo.png");
			File file=new File(logoPath);
			if(file.isFile()){
				QRCodeUtils.addLogo_QRCode(qrcodeImg, file);
			}
		}
		
		if(StringUtils.isEmpty(addCard)){
			addCard = "false";
		}
		
		qrcodeImg=getTileImage(qrcodeImg, backgroundImage,"right_bottom",addCard,name,phone);
		
		response.setContentType("image/png");// 设置相应类型,告诉浏览器输出的内容为图片
		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
		response.setHeader("Cache-Control", "no-cache");

		try {
			ImageIO.write(qrcodeImg, "png", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}	
		
	}
	
	
	
	/**
	 * 画图片
	 *
	 */
	private BufferedImage getTileImage(BufferedImage qrcodeImg,BufferedImage imagePic,String position,String addCard,String name,String phone){
		
		//获取底图的宽高
		int width=imagePic.getWidth();
		int height = imagePic.getHeight();
		int fillWhiteHeight=5;
		
		int qrcodeWidth=width/4;
		if(qrcodeWidth>200){
			qrcodeWidth=200+(qrcodeWidth-200)/3;
		}

		//设置二维码的宽、高、
		int qrcodeHeight =qrcodeWidth;
		BufferedImage tag = null;
		Graphics2D graphics = null;

		if(addCard.equals("true")){
				tag = new BufferedImage(width+30, height+100, BufferedImage.TYPE_INT_RGB);
				graphics=tag.createGraphics();
				graphics.setBackground(Color.white);
				graphics.fillRect(0, 0, width+30, height+120);
				
				String line1 = "详情咨询："+name;
				String line2 = "联系方式："+phone;
				
				graphics.setFont(new Font("宋体", Font.PLAIN, 20));
				graphics.setColor(Color.BLACK);
				
			
				
				graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
				graphics.drawString(line1, 15, height+45);
				graphics.drawString(line2, 15, height+75);
				
				
				 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				graphics.drawImage(imagePic, 15, 15, width, height, null); 
		}else{
		       tag = new BufferedImage(width+30, height+30, BufferedImage.TYPE_INT_RGB);
		       graphics=tag.createGraphics();
		       
		       graphics.setBackground(Color.white);
		       graphics.fillRect(0, 0, width+30, height+120);
				
		       //字体平滑
		       graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				
		       graphics.drawImage(imagePic, 15, 15, width, height, null); 
			
		}
		
		//确定图片在哪个位置
		if("middle".equals(position)){
			qrcodeWidth=width/2;
			qrcodeHeight =qrcodeWidth;
			fillWhiteHeight=60;
			graphics.drawImage(qrcodeImg, width/2-qrcodeWidth/2,height-qrcodeHeight-fillWhiteHeight,qrcodeWidth,qrcodeHeight,null);

		}else if("right_bottom".equals(position)){
			qrcodeWidth=width/4;
			qrcodeHeight =qrcodeWidth;	
			graphics.drawImage(qrcodeImg, width-qrcodeWidth,height-qrcodeHeight,qrcodeWidth,qrcodeHeight,null);
			
		}else if("left_bottom".equals(position)){
			graphics.drawImage(qrcodeImg, 0,height-qrcodeHeight-fillWhiteHeight,qrcodeWidth,qrcodeHeight,null);
		
		}else if("left_top".equals(position)){
			graphics.drawImage(qrcodeImg, 0,fillWhiteHeight,qrcodeWidth,qrcodeHeight,null);
			
		}else if("right_top".equals(position)){
			graphics.drawImage(qrcodeImg, width-qrcodeWidth,fillWhiteHeight,qrcodeWidth,qrcodeHeight,null);
		}
		return tag;
	}
	
	
	
}
